package com.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.constants.Constants;
import com.crmeb.core.exception.CrmebException;
import com.utils.ThreadLocalUtil;
import com.zbkj.crmeb.chant.model.ChannelMerchantRenewal;
import com.zbkj.crmeb.chant.service.ChannelMerchantRenewalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.common.CheckFrontToken;
import com.crmeb.core.common.CommonResult;
import com.utils.RequestUtil;

import java.util.Date;

//token验证拦截器

public class FrontTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private CheckFrontToken checkFrontToken;
    @Autowired
    private ChannelMerchantRenewalService channelMerchantRenewalService;

    //程序处理之前需要处理的业务
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        String token = checkFrontToken.getTokenFormRequest(request);
        String merId = request.getHeader(Constants.HEADER_MERCHANT_ID);
        if (StringUtils.isBlank(merId)) {
            throw new CrmebException("商户信息丢失!");
        }
		/*ChannelMerchantRenewal merchantRenewal = channelMerchantRenewalService.getOne(Wrappers.<ChannelMerchantRenewal>lambdaQuery().eq(ChannelMerchantRenewal::getMerId,merId).orderByDesc(ChannelMerchantRenewal::getId).last("LIMIT 1"));
		if(merchantRenewal == null || merchantRenewal.getExpirationTime().before(new Date())){
		    throw new CrmebException("对不起，该小程序已打烊！");
		}*/
        ThreadLocalUtil.remove();
        if(token == null || token.isEmpty()){
            //判断路由，部分路由不管用户是否登录都可以访问
            boolean result = checkFrontToken.checkRouter(RequestUtil.getUri(request));
            if(result){
                return true;
            }

            response.getWriter().write(JSONObject.toJSONString(CommonResult.unauthorized()));
            return false;
        }

        Boolean result = checkFrontToken.check(token, request);
        if(!result){
            response.getWriter().write(JSONObject.toJSONString(CommonResult.unauthorized()));
            return false;
        }
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }

}
